package com.array.www.controller;

import com.array.www.entities.CommonResult;
import com.array.www.entities.Payment;
import com.array.www.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Created by Mr.Array
 * @Description TODO
 * @Date 2021/5/13 10:19 下午
 */
@Slf4j
@RestController
public class PaymentController {

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    /**
     * 写操作 ------------------@PostMapping
     * @param payment
     * @return
     */
    @PostMapping(value = "payment/create")
    public CommonResult create(Payment payment) {
        int result = paymentService.create(payment);
        log.info("******插入结果******"+ result);
        if (result > 0) {
            return new CommonResult(200, "插入成功！",result);
        } else {
            return new CommonResult(444,"插入失败～");
        }
    }

    /**
     * 读操作 ----------------@GetMapping
     * @param id
     * @return
     */
    @GetMapping(value = "payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        log.info("******插入结果******"+ payment);
        if (payment != null) {
            return new CommonResult(200, "查询成功！**** serverPort"+serverPort ,payment);
        } else {
            return new CommonResult(444,"没有对应记录～ID:"+id, null);
        }
    }

    @GetMapping("/payment/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        services.forEach((s)-> {
            log.info("element:" + s);
        });
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PROVIDER-SERVICE");
        instances.forEach((item)-> {
            log.info(item.getInstanceId() +"\t"+ item.getHost()+"\t"+item.getPort() +"\t"+ item.getUri());
        });
        return discoveryClient;
    }

    @GetMapping(value = "/payment/lb")
    public String getPaymentLB () {
        return serverPort;
    }


    @GetMapping("/payment/feign/timeout")
    public String paymentFeignTimeout() {
        try {
            TimeUnit.SECONDS.sleep(3L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }
}
